package com.tg.app.activity.device.settings;

import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.core.util.Consumer;

import com.demo.view.SettingItemSwitchView;
import com.demo.view.SettingItemTextView;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Instruction;
import com.tange.core.device.facade.Status;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tange.module.device.feature.DeviceFeature_;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.adapter.AlarmAdapter;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.camera.CameraHelper;
import com.tg.app.helper.AlertSoundHelper;
import com.tg.app.helper.AppHelper;
import com.tg.app.util.LogUtils;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.http.entity.AlarmToneCapBean;
import com.tg.data.http.entity.DeviceBellBean;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;

public class AlertSoundActivity extends DeviceSettingsBaseActivity{
    private static final String TAG = "AlertSoundActivity";
    private static final int STATE_ON = 1;
    private static final int STATE_OFF = 0;
    public SettingItemSwitchView swBuzzer;
    private DeviceSettingsInfo info;
    private DeviceFacade deviceFacade;
    private DeviceFeature deviceFeature;
    private AlarmToneCapBean alarmToneCapBean;

    private String idAlarmTone;

    public static final String EXT_AUDIO_CODECS = "ext_audio_codecs";
    public static final String EXT_CUSTOM_SET = "ext_custom_set";
    private SettingItemTextView alertSoundView;
    private boolean alarmToneCap = false;

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onSetupFailed() {
        swBuzzer.setChecked(!swBuzzer.isChecked());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        hideActionBar();
        setContentView(R.layout.activity_alert_sound);
        getIntentData();
        initView();
        getAlarmToneCap();
        AlertSoundHelper.getInstance().findVoiceFile(this, info.uuid);
        LogUtils.matTrackCustomKVEvent(getBaseContext(), "event_click", "BELL");
    }

    private void getAlarmToneCap(){
        if (deviceFacade.connected()){
            if (deviceFeature != null && deviceFeature.supportAlarmTone) {
                if (!alarmToneCap){
                    CameraHelper.getAlarmToneCap(deviceFacade);
                    alarmToneCap = true;
                }
            }
        }
    }
    private void registerICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().observeOnReceive(instructionConsumer);
        }
    }

    private void unregisterICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().unObserveOnReceive(instructionConsumer);
        }
    }

    private void getIntentData() {
        Intent intent = getIntent();
        info = intent.getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        deviceFacade = new DeviceFacade(info.uuid);
        registerICameraListener();
        deviceFacade.connect();
        alarmToneCapBean = new AlarmToneCapBean(info.uuid, false);
        Box<DeviceFeature> featureBox = DeviceFeatureObjectBox.getDeviceFeature();
        assert featureBox != null;
        deviceFeature = featureBox.query().equal(DeviceFeature_.uuid, info.uuid).build().findFirst();
    }

    private void setSwitchBuzzerState() {
        swBuzzer.setChecked(info.buzzerOn == STATE_ON);
        swBuzzer.setOnClickListener(v -> {
            //当前模式，mode: 1- on, 0- off
            if (!TGDevice.getInstance().isNetwork(deviceFacade)){
                TGToast.showToast(R.string.txt_network_anomaly);
                swBuzzer.setChecked(!swBuzzer.isChecked());
            }else{
                setBuzzerCmd(swBuzzer.isChecked()? STATE_ON : STATE_OFF);
                showAlertItem();
            }
        });
        showAlertItem();
    }

    private void showAlertItem() {
        if (CameraHub.getInstance().isEnableLocalApConnect()) {
            alertSoundView.setVisibility(View.GONE);
            swBuzzer.showLine(false);
        }else{
            if (swBuzzer.isChecked()) {
                if (deviceFeature != null && deviceFeature.supportAlarmTone && deviceFeature.supportBuzzer) {
                    alertSoundView.setVisibility(View.VISIBLE);
                    swBuzzer.showLine(true);
                }else{
                    hideAlertSoundView();
                }
            } else {
                hideAlertSoundView();
            }
        }
    }

    private void hideAlertSoundView() {
        swBuzzer.showLine(false);
        alertSoundView.setVisibility(View.GONE);
    }

    @Override
    protected void initView() {
        swBuzzer = findViewById(R.id.rl_alert_sound);
        backClickEvent();
        alertSoundView = findViewById(R.id.rl_settings_change_alert_sound);
        alertSoundView.setOnClickListener(v -> goToAlertSoundList());
        setSwitchBuzzerState();
        if (!StringUtils.isEmpty(mTitle)){
            swBuzzer.setText(mTitle);
        }
        setSound();
    }

    private void goToAlertSoundList() {
        Intent intent = new Intent(AlertSoundActivity.this, AlertSoundListActivity.class);
        intent.putExtra(EXT_DEVICE_INFO, info);
        intent.putExtra(Camera.EXT_UUID, info.uuid);
        intent.putExtra(SETTING_ITEM_TITLE, mTitle);
        intent.putExtra(AlertSoundListActivity.EXT_DEVICE_ALAEM_TONE_CAP, alarmToneCapBean);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            if (!deviceFacade.connected()){
                deviceFacade.connect();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
        }
    }


    private final Consumer<ConnectStatus> connectStatusConsumer = connectStatus -> {
        if (connectStatus.getStatus() == Status.SUCCESS){
            TGLog.d(TAG,"连接成功");
            getAlarmToneCap();
        }else if (connectStatus.getStatus() == Status.FAILED){
            TGLog.d(TAG,"连接失败");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterICameraListener();
    }


    private void setBuzzerCmd(int on) {
        if (deviceFacade != null) {
            startSendui();
            info.buzzerOn = on;
            AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_SET_BUZZER_REQ, AVIOCTRLDEFs.Tcis_SetBuzzerReq.parseContent(on));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            setAlertSoundText(AlertSoundHelper.getInstance().getShowText());
        }
    }


    private final Consumer<Instruction> instructionConsumer = instruction -> {
        if (instruction == null) {
            return;
        }
        final int type = instruction.getId();
        final byte[] data = instruction.getData();
        receiveIOCtrlData(type, data);
    };

    public void receiveIOCtrlData(final int type, final byte[] data) {
        runOnUiThread(() -> {
            if (type == AVIOCTRLDEFs.TCI_CMD_SET_BUZZER_RESP) {
                TGLog.d(TAG,"TCI_CMD_SET_BUZZER_RESP");
                showToast(R.string.setting_success);
                completeSend();
                sendUpdateSettingBroadcast(info);
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_ALARMTONE_CAP_RESP) {
                TGLog.d(TAG,"TCI_CMD_GET_ALARMTONE_CAP_RESP");
                alarmToneCapBean.receiveIOCtrlData(data);
                int alarmTone = Packet.byteArrayToInt_Little(data, 28);
                idAlarmTone = String.valueOf(alarmTone);

                if (alarmToneCapBean.nSupportedAudioCodecs > 0) {
                    AlertSoundHelper.getInstance().setIdAlarmTone(idAlarmTone, ResourcesUtil.getString(R.string.txt_current_voice));
                    AlertSoundHelper.getInstance().setSelectAlarmTone(idAlarmTone);
                    setAlertSoundText(AlertSoundHelper.getInstance().getShowText());
                } else {
                    TGThreadPool.executeOnUiThread(() -> {
                        alertSoundView.setVisibility(View.GONE);
                        swBuzzer.showLine(false);
                    });
                }
            }
        });
    }

    private void setSound(){
        String text = getString(R.string.alarm_sound_default);

        List<DeviceBellBean> list = new ArrayList<>();
        TGLog.d(TAG,"idAlarmTone = " + idAlarmTone);
        DeviceBellBean defBean = new DeviceBellBean(AlarmAdapter.ALARM_DEFAULT, text);
        list.add(defBean);


        AlertSoundHelper.getInstance().setCloudList(list);

    }


    private void setAlertSoundText(String text){
        alertSoundView.setContent("");
    }
}
